package com.bsoft.gol.hcs.his.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.base.BaseHisPlateformXmlRequest;
import com.bsoft.gol.hcs.base.BaseHisPlateformXmlResponse;
import com.bsoft.gol.hcs.base.MsgHeaderRequest;
import com.bsoft.gol.hcs.enumcase.InspectionEmum;
import com.bsoft.gol.hcs.his.bean.request.ListQueryHisReq;
import com.bsoft.gol.hcs.his.bean.response.ListHistoryRecordMsgBodyResponse;
import com.bsoft.gol.hcs.his.bean.response.ListHistoryRecordResponse;
import com.bsoft.gol.hcs.his.bean.response.OutpatientPageInfoQueryBean;
import com.bsoft.gol.hcs.his.service.IPatientRecordQueryService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import com.bsoft.gol.hcs.utils.JSONDateUtil;
import com.bsoft.gol.hcs.utils.WhisClientUtil;
import com.bsoft.gol.hcs.visitrecord.bean.qo.HospitalVisitsRecordListQo;
import com.bsoft.gol.hcs.visitrecord.bean.qo.InspectionReportRecordsReq;
import com.bsoft.gol.hcs.visitrecord.bean.vo.*;
import com.bsoft.gol.hcs.visitrecord.dao.VrApplicationFormDetailDAO;
import com.bsoft.gol.hcs.visitrecord.dao.VrApplicationFormRecordDAO;
import com.bsoft.gol.hcs.visitrecord.dao.VrInpatientVisitRecordDAO;
import com.bsoft.gol.hcs.visitrecord.dao.VrOutpatientVisitRecordDAO;
import com.bsoft.gol.hcs.visitrecord.entity.VrApplicationFormDetail;
import com.bsoft.gol.hcs.visitrecord.entity.VrSurgicalRecord;
import com.bsoft.gol.hcs.visitrecord.entity.VrVisitDiagnosisVo;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import ctd.util.xml.jaxb.JAXBUtils;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import org.apache.commons.collections.CollectionUtils;
import org.atag.dao.model.SimplePageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:FangZhiyi
 * @Description
 * @Data Created in 2020/10/28 10:08
 * @Moddified By:
 */
@SsdevService("patientRecordService")
public class PatientRecordQueryServiceImpl implements IPatientRecordQueryService {
    private final static Logger logger = LoggerFactory.getLogger(PatientRecordQueryServiceImpl.class);

    @Value("${platform_url}")
    public String platformUrl;

    @Autowired
    private VrOutpatientVisitRecordDAO vrOutpatientVisitRecordDAO;
    @Autowired
    private VrInpatientVisitRecordDAO vrInpatientVisitRecordDAO;
    @Autowired
    private VrApplicationFormRecordDAO vrApplicationFormRecordDAO;
    @Autowired
    private VrApplicationFormDetailDAO vrApplicationFormDetailDAO;
    /**
     * @Author:FangZhiyi
     * @Description  查询门诊记录
     * @Params  [queryHisReq]
     * @Return  org.atag.core.base.BaseResponse
     * @Data Created in 2020/10/28 16:38
     * @Moddified By:
     */
    @Override
    @RpcService
    public SimplePageInfo<OutpatientRecordListVo> queryOutpatientRecords(ListQueryHisReq queryHisReq) {
//        String jsonContext = JSONDateUtil.readFile("queryOutpatientRecords");
//        List<OutpatientRecordVo> outpatientRecordVoList =  JSONArray.parseArray(jsonContext, OutpatientRecordVo.class);

/*        OutpatientPageInfoQueryBean queryBean = new OutpatientPageInfoQueryBean();

        queryBean.setBeginTime(queryHisReq.getBeginDate());
        queryBean.setEndTime(queryHisReq.getEndDate());
        queryBean.setPageNo(queryHisReq.getPageNo().toString());
        queryBean.setPageSize(queryHisReq.getPageSize().toString());
        queryBean.setPatientId(queryHisReq.getPatientIdList().get(0).toString());*/
        BaseResponse<SimplePageInfo<OutpatientRecordListVo>> baseResponse = new BaseResponse<>();
        if(CommonUtils.isNotEmpty(queryHisReq.getPatientIdList()) && CommonUtils.isNotEmpty(queryHisReq.getOrganizationId())){
            HospitalVisitsRecordListQo qo = new HospitalVisitsRecordListQo();
            qo.setOrganizationId(queryHisReq.getOrganizationId());
            qo.setPatientId(queryHisReq.getPatientIdList().get(0).getPatientId());
            SimplePageInfo<OutpatientRecordListVo> outpatientRecordVoSimplePageInfo = vrOutpatientVisitRecordDAO.queryOutpatientRecordVos(qo);
            return outpatientRecordVoSimplePageInfo;
        }
        SimplePageInfo<OutpatientRecordListVo> simplePageInfo =new SimplePageInfo<>();
        simplePageInfo.setTotal(0L);
        return simplePageInfo;
    }

    /**
     * @description: 健康档案对接HIS，获取门诊记录列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2019/11/27 15:33
     * @param: queryBean
     * @return: hcn.protocol.phr.healthrecord.OutpatientPageInfoBean
     */
    @RpcService
    public List<OutpatientRecordVo> queryHistoryRecordList(OutpatientPageInfoQueryBean queryBean) {
        logger.info("WebCloudClinicServiceImpl.outpatientPageInfo 入参：{}", queryBean);
        BaseResponse<List<OutpatientRecordVo>> baseResponse = new BaseResponse<>();
        //门诊记录列表
        List<OutpatientRecordVo> recordList = new ArrayList<>();
        //门诊记录
        OutpatientRecordVo recordBean;
        //历史诊断列表
        List<VrVisitDiagnosisVo> diagnosticInformationList = null;

        String serviceName = InspectionEmum.ListHistoryRecord.getCode();

        //组装xml请求入参
        BaseHisPlateformXmlRequest<OutpatientPageInfoQueryBean> xmlRequest = new BaseHisPlateformXmlRequest<OutpatientPageInfoQueryBean>();
        //组装MsgHeader
        MsgHeaderRequest msgHeader = new MsgHeaderRequest();
        msgHeader.setMsgType(InspectionEmum.ListHistoryRecord.getValue());
        msgHeader.setMsgVersion(Constants.MSG_VERSION);
        msgHeader.setOrganization(queryBean.getOrganizationId());
        msgHeader.setSender(Constants.SERVICE_TYPE_SERVICE);
        msgHeader.setServiceType(Constants.SERVICE_TYPE_SERVICE);
        xmlRequest.setMsgHeader(msgHeader);
        //组装MsgBody
        xmlRequest.setMsgBody(queryBean);

        String queryXml = JAXBUtils.object2Xml(new Class[]{BaseHisPlateformXmlRequest.class, OutpatientPageInfoQueryBean.class}, xmlRequest);

        try {
            //组装soapXml数据
            queryXml = WhisClientUtil.getSoapXmlWithOutBSXml(serviceName, queryXml);
            String xmlStr = WhisClientUtil.getStringDataFromPhis(platformUrl, queryXml);
            BaseHisPlateformXmlResponse xmlResponse = JAXBUtils.xml2Object(xmlStr, BaseHisPlateformXmlResponse.class);
            if (null != xmlResponse) {
                //转换数据返回的data字符串
                xmlResponse = JSONObject.parseObject(JSONUtils.writeValueAsString(xmlResponse), BaseHisPlateformXmlResponse.class);

                if (null != xmlResponse) {
                    BaseHisPlateformXmlResponse.MsgBody msgBody = xmlResponse.getMsgBody();

                    if (msgBody != null) {
                        String status = msgBody.getStatus();

                        if (status != null && "true".equals(status)) {
                            if (null != xmlResponse.getMsgBody().getData()) {
                                String data = String.valueOf(xmlResponse.getMsgBody().getData());
                                if (CommonUtils.isNotEmpty(data)) {
                                    data = data.replace("UTF-16", "UTF-8");
                                    ListHistoryRecordMsgBodyResponse dataResponse = JAXBUtils.xml2Object(data, ListHistoryRecordMsgBodyResponse.class);
                                    if (CommonUtils.isNotEmpty(dataResponse)) {
                                        if (CommonUtils.isNotEmpty(dataResponse.getVisitLists())) {
                                            for (ListHistoryRecordResponse listHistoryRecordResponse : dataResponse.getVisitLists()) {
                                                recordBean = new OutpatientRecordVo();
                                                recordBean.setOrganizationId(listHistoryRecordResponse.getOrganizationId());
                                                recordBean.setOrganizationName(listHistoryRecordResponse.getOrganizationName());
                                                recordBean.setDepartmentId(listHistoryRecordResponse.getDepartmentId());
                                                recordBean.setDepartmentName(listHistoryRecordResponse.getDepartmentName());
                                                recordBean.setDoctorId(listHistoryRecordResponse.getDoctorId());
                                                recordBean.setDoctorName(listHistoryRecordResponse.getDoctorName());
                                                recordBean.setStartTime(listHistoryRecordResponse.getDiagnosisDate());
                                                recordBean.setVisitNo(listHistoryRecordResponse.getAdmNumber());
                                                recordBean.setPatientMedicalCardNumber(listHistoryRecordResponse.getPatientMedicalCardNumber());
                                                diagnosticInformationList = new ArrayList<>();
                                                VrVisitDiagnosisVo vrVisitDiagnosis = new VrVisitDiagnosisVo();
                                                vrVisitDiagnosis.setDiseasesName(listHistoryRecordResponse.getDiagnosisName());
                                                diagnosticInformationList.add(vrVisitDiagnosis);
                                                recordBean.setDiagnosisList(diagnosticInformationList);
                                                recordList.add(recordBean);
                                            }
                                            return recordList;
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        baseResponse.setCode(ResultCode.ERROR);
                        baseResponse.setMessage(msgBody.getDetail());
                    }
                } else {
                    baseResponse.setCode(ResultCode.ERROR);
                    baseResponse.setMessage("查询历史就诊记录失败！");
                }
            }
        } catch (Exception e) {
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMessage("查询历史就诊记录失败！");

        }

        return null;
    }


    /**
     * @Author:FangZhiyi
     * @Description  查询住院记录
     * @Params  [queryHisReq]
     * @Return  org.atag.core.base.BaseResponse
     * @Data Created in 2020/10/28 16:39
     * @Moddified By:
     */
    @Override
    @RpcService
    public SimplePageInfo<InpatientVisitRecordListVo> queryHospitalRecords(ListQueryHisReq queryHisReq) {
//        String jsonContext = JSONDateUtil.readFile("queryHospitalRecords");
//        List<InpatientVisitRecordVo> inpatientVisitRecordVoList =  JSONArray.parseArray(jsonContext, InpatientVisitRecordVo.class);
//        BaseResponse<List<InpatientVisitRecordVo>> baseResponse = new BaseResponse<>();
//        baseResponse.setData(inpatientVisitRecordVoList);
        BaseResponse<SimplePageInfo<InpatientVisitRecordListVo>> baseResponse = new BaseResponse<>();
        if(CommonUtils.isNotEmpty(queryHisReq.getPatientIdList()) && CommonUtils.isNotEmpty(queryHisReq.getOrganizationId())){
            HospitalVisitsRecordListQo qo = new HospitalVisitsRecordListQo();
            qo.setOrganizationId(queryHisReq.getOrganizationId());
            qo.setPatientId(queryHisReq.getPatientIdList().get(0).getPatientId());
            SimplePageInfo<InpatientVisitRecordListVo> inpatientVisitRecordVoSimplePageInfo = vrInpatientVisitRecordDAO.queryInpatientVisitRecordVos(qo);
            return inpatientVisitRecordVoSimplePageInfo;
        }
        SimplePageInfo<InpatientVisitRecordListVo> simplePageInfo =new SimplePageInfo<>();
        simplePageInfo.setTotal(0L);
        return simplePageInfo;
    }

    /**
     * @Author:FangZhiyi
     * @Description  查询检验、检查、治疗记录
     * @Params  [queryHisReq]
     * @Return  org.atag.core.base.BaseResponse
     * @Data Created in 2020/10/28 16:39
     * @Moddified By:
     */
    @Override
    @RpcService
    public List<ApplicationFormRecordVo> queryInspectionReportRecords(ListQueryHisReq queryHisReq) {
//        String jsonContext = JSONDateUtil.readFile("queryInspectionReportRecords");
//        List<ApplicationFormRecordVo> applicationFormRecordVoList =  JSONArray.parseArray(jsonContext, ApplicationFormRecordVo.class);
        InspectionReportRecordsReq reportRecordsReq=new InspectionReportRecordsReq();
        reportRecordsReq.setBillCategoryCode(queryHisReq.getBillCategoryCode());
        reportRecordsReq.setQueryType(queryHisReq.getQueryType());
        if(!CollectionUtils.isEmpty(queryHisReq.getPatientIdList())){
            reportRecordsReq.setPatientId(queryHisReq.getPatientIdList().get(0).getPatientId());
        }
        if(!CollectionUtils.isEmpty(queryHisReq.getPatientIdentityCardList())){
            reportRecordsReq.setCardType(queryHisReq.getPatientIdentityCardList().get(0).getCardType());
            reportRecordsReq.setCardNumber(queryHisReq.getPatientIdentityCardList().get(0).getCardNumber());
        }
        if(!CollectionUtils.isEmpty(queryHisReq.getPatientMedicalCardNumberList())){
            reportRecordsReq.setPatientMedicalCardType(queryHisReq.getPatientMedicalCardNumberList().get(0).getPatientMedicalCardType());
            reportRecordsReq.setPatientMedicalCardNumber(queryHisReq.getPatientMedicalCardNumberList().get(0).getPatientMedicalCardNumber());
        }
        List<ApplicationFormRecordVo> applicationFormRecordVoList =  vrApplicationFormRecordDAO.queryInspectionReportRecords(reportRecordsReq);
        if(!CollectionUtils.isEmpty(applicationFormRecordVoList)){
            for (ApplicationFormRecordVo record: applicationFormRecordVoList) {
                List<VrApplicationFormDetail> detailList=new ArrayList<>();
                detailList=vrApplicationFormDetailDAO.queryDetailByApplicationId(record.getApplicationId());
                record.setDetails(detailList);
            }
        }

        return applicationFormRecordVoList;
    }


    /**
     * @Author:FangZhiyi
     * @Description  查询手术记录
     * @Params  [queryHisReq]
     * @Return  org.atag.core.base.BaseResponse
     * @Data Created in 2020/10/28 16:41
     * @Moddified By:
     */
    @Override
    @RpcService
    public List<VrSurgicalRecord> surgicalRecords(ListQueryHisReq queryHisReq) {
        String jsonContext = JSONDateUtil.readFile("surgicalRecords");
        List<VrSurgicalRecord> surgicalRecordList =  JSONArray.parseArray(jsonContext, VrSurgicalRecord.class);
        return surgicalRecordList;
    }

    /**
     * @Author:FangZhiyi
     * @Description  查询发药记录
     * @Params  [queryHisReq]
     * @Return  org.atag.core.base.BaseResponse
     * @Data Created in 2020/10/28 16:39
     * @Moddified By:
     */
    @Override
    @RpcService
    public List<DispensingRecordVo> queryDispensingRecords(ListQueryHisReq queryHisReq) {
        String jsonContext = JSONDateUtil.readFile("queryDispensingRecords");
        List<DispensingRecordVo> dispensingRecordVoList =  JSONArray.parseArray(jsonContext, DispensingRecordVo.class);
        return dispensingRecordVoList;
    }
}
